package cn.mysource.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Date;

@Slf4j
public class RequestTimeFilter implements GatewayFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1.记录请求路径
        log.info("请求地址为：" + exchange.getRequest().getURI().getPath());

        // 2.存储开始时间
        exchange.getAttributes().put("startTime", new Date().getTime());

        // 3.执行完成之后
        return chain.filter(exchange).then(
                Mono.fromRunnable(() -> {
                    // 开始时间
                    Long startTime = exchange.getAttribute("startTime");
                    // 结束时间
                    Long endTime = (System.currentTimeMillis() - startTime);
                    // 打印当前请求耗时
                    log.info(exchange.getRequest().getURI().getRawPath() + ": " + endTime + "ms");
                })
        );
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
